package edu.sjsu.itack.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.sjsu.itack.bl.UserBl;
import edu.sjsu.itack.entity.User;
import edu.sjsu.itack.util.ITackException;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet  {
	private static final long serialVersionUID = 1L;

	private UserBl userBl;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void init() throws ServletException {
		userBl = new UserBl();
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		StringBuilder status = new StringBuilder("{Error : ");
		User user = null;
		try {
			user = userBl.validateUser(email, password);
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			request.getRequestDispatcher("board.jsp").forward(request, response);
		} catch (ITackException e) {
			status.append(e.getLocalizedMessage());
		request.setAttribute("error", e.getLocalizedMessage());
			//response.getWriter().write(status.toString());
		request.getRequestDispatcher("signin.jsp").forward(request, response);
		}
	}

}
